"use strict";
const BaseController = require("./base");

class CommentController extends BaseController {
  // 对文章发表评论
  async create() {
    const {ctx} = this;
    const {replyedPerson, article, commitPerson, commentText} = ctx.request.body;
    const obj = {replyedPerson, article, commitPerson, commentText};
    let res = await ctx.model.Comment.create(obj);
    if (res._id) {
      await ctx.model.Article.findByIdAndUpdate(article, {
        $inc: { commentCount: 1 },
      });
      this.success({
        id: res._id,
        commentText: res.commentText,
      });
    } else {
      this.error("评论失败！");
    }
  }

  // 获取评论列表
  async commentsList() {
    const {ctx} = this;
    const article = ctx.query.article
    const list = await ctx.model.Comment.find({
      article,
      replyedPerson: {"$exists": false}
    }).populate("commitPerson").sort({createdAt: -1});
    // list.forEach((item) => {
    //   if (item.subComments.length) {
    //     let arr = []
    //     item.subComments.forEach(async it => {
    //       let temp = await ctx.model.Comment.findOne({_id: it._id}).populate("commitPerson").populate("replyedPerson");
    //       arr.push(temp)
    //     })
    //     item.subComments = arr;
    //   }
    // })
    this.success(list);
  }

  async reply() {
    const {ctx} = this;
    const {superComment, replyedPerson, article, commitPerson, commentText} = ctx.request.body;
    const currentComment = await ctx.model.Comment.findOne({_id: superComment})
    const obj = {replyedPerson, article, commitPerson, commentText};
    let res = await ctx.model.Comment.create(obj);
    let subComment = await ctx.model.Comment.findOne({_id: res._id}).populate("commitPerson").populate("replyedPerson")
    console.log(subComment, "99999999999999999")
    let temp = {
      replyedPerson: { // 被回复的人
        nickname: subComment.replyedPerson.nickname,
        avatar: subComment.replyedPerson.avatar,
        id: subComment.replyedPerson._id
      },
      article: subComment.article,
      commitPerson: { // 回复的人
        nickname: subComment.commitPerson.nickname,
        avatar: subComment.commitPerson.avatar,
        id: subComment.commitPerson._id
      },
      // 评论内容
      commentText: subComment.commentText,
    }
    currentComment.subComments.push(temp)
    console.log(currentComment)
    currentComment.save()
    this.success({
      message: "回复成功"
    });
    await ctx.model.Article.findByIdAndUpdate(article, {
      $inc: { commentCount: 1 },
    });

  }
}

module.exports = CommentController;
